<template>
  <div class="product-detail">
    <div class="header">
      <el-steps
        :space="200"
        :active="currentStep"
        finish-status="success"
        class="steps"
      >
        <el-step title="商品基本信息" />
        <el-step title="添加库存信息" />
        <el-step title="添加移动端详情" />
      </el-steps>
    </div>
    <div class="content">
      <el-card shadow="never">
        <div>
          <el-form
            ref="form"
            :model="productForm"
            :rules="rules"
            label-width="100px"
            size="mini"
            class="from"
          >
            <!-- 步骤一 -->
            <div v-show="currentStep == 1" class="stepone">
              <div class="header">基本信息</div>
              <el-row :gutter="20">
                <el-col :span="8" :offset="0">
                  <el-form-item label="商品名称">
                    <el-input
                      v-model="productForm.name"
                      placeholder="商品名称"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="商品编码">
                    <el-input
                      v-model="productForm.productSn"
                      placeholder="商品编码"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="商品分类">
                    <el-select
                      v-model="productForm.productCategoryId"
                      placeholder="商品分类"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in categorys"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="商品品牌">
                    <el-select
                      v-model="productForm.brandId"
                      placeholder="商品品牌"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in brandList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="15" :offset="0">
                  <el-form-item label="商品描述">
                    <el-input
                      v-model="productForm.description"
                      placeholder="商品描述"
                      type="textarea"
                    >a</el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="header">商品属性</div>
              <el-row :gutter="20">
                <el-col :span="8" :offset="0">
                  <el-form-item label="商品原价">
                    <el-input-number
                      v-model="productForm.originalPrice"
                      :min="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="促销类型">
                    <el-select
                      placeholder="没有促销使用原价"
                      clearable
                      filterable
                      value=""
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="活动价格">
                    <el-input-number
                      v-model="productForm.promotionPrice"
                      :min="0"
                      value="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="16">
                  <el-form-item label="重量(kg)">
                    <el-input-number v-model="productForm.weight" :min="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="审核状态">
                    <el-switch
                      v-model="productForm.verifyStatus"
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="是否上架">
                    <el-switch
                      v-model="productForm.publishStatus"
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12" :offset="0">
                  <el-form-item label="缩略图">
                    <el-upload
                      class="uploader"
                      action="http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss"
                      :headers="token"
                      :show-file-list="false"
                      :on-success="handleUploadPicSuccess"
                    >
                      <img
                        v-if="productForm.pic"
                        :src="productForm.pic"
                        class="pic"
                      >
                      <i v-else class="el-icon-plus uploader-icon" />
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="header">其他信息</div>
              <el-row :gutter="20">
                <el-col :span="8" :offset="0">
                  <el-form-item label="推荐状态">
                    <el-switch
                      v-model="productForm.recommendStatus"
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="新品状态">
                    <el-switch
                      v-model="productForm.newStatus"
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="预告商品">
                    <el-switch
                      v-model="productForm.previewStatus"
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="搜索关键词">
                    <el-input
                      v-model="productForm.keywords"
                      placeholder="关键词"
                      size="normal"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="库存预警">
                    <el-input-number v-model="productForm.lowStock" :min="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="商品排序">
                    <el-input-number
                      v-model.number="productForm.sort"
                      :min="0"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" :offset="0">
                  <el-form-item label="商品服务">
                    <el-checkbox-group v-model="productForm.serviceIds">
                      <el-checkbox label="1">无忧退货</el-checkbox>
                      <el-checkbox label="2">快速退款</el-checkbox>
                      <el-checkbox label="3">免费包邮</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 步骤二 -->
            <div v-show="currentStep == 2" class="steptwo">
              <div class="header">商品sku信息</div>
              <el-row :gutter="20">
                <el-col :span="12" :offset="0">
                  <el-form-item label="标题" size="normal">
                    <el-input
                      v-model="productForm.detailTitle"
                      placeholder="标题"
                      size="normal"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12" :offset="0">
                  <el-form-item label="副标题" size="normal">
                    <el-input
                      v-model="productForm.detailDesc"
                      placeholder="副标题"
                      size="normal"
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12" :offset="0">
                  <el-form-item label="画册图片">
                    <el-upload
                      ref="uploadImgs"
                      class="uploader"
                      action="http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss"
                      :headers="token"
                      multiple
                      accept=".png,.jpg,.jpeg,.webp"
                      :show-file-list="false"
                      :file-list="uploadImages"
                      :on-success="handleImageSuccess"
                      :limit="5"
                      :on-exceed="onExceed"
                    >
                      <div v-if="uploadImages.length" class="imgs">
                        <div
                          v-for="(item, index) in uploadImages"
                          :key="item"
                          class="item"
                        >
                          <img :src="item.path" alt="" srcset="" class="pic">
                          <i
                            class="el-icon-close deleteImage"
                            @click.stop="handleDelImage(index)"
                          />
                        </div>
                      </div>
                      <i v-else class="el-icon-plus uploader-icon" />
                      <div slot="tip" class="el-upload__tip">
                        只能上传jpg/png文件，且不超过500kb
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24" :offset="0">
                  <el-form-item label="sku设置" size="normal">
                    <div v-if="skuColors.length" class="color-sku">
                      <span class="title">颜色:</span>
                      <el-checkbox-group v-model="checkedColors">
                        <div
                          v-for="(color, index) in skuColors"
                          :key="color"
                          class="checkbox-item"
                        >
                          <el-checkbox :label="color">
                            {{ color }}
                          </el-checkbox>
                          <el-button
                            type="text"
                            size="mini"
                            style="color: red"
                            class="delbtn"
                            @click="handleDelColorSku(index)"
                          >删除</el-button>
                        </div>
                      </el-checkbox-group>
                    </div>
                    <div v-if="skuSizes.length" class="size-sku">
                      <span class="title">大小:</span>
                      <el-checkbox-group v-model="checkedSkuSizes">
                        <div
                          v-for="(size, index) in skuSizes"
                          :key="size"
                          class="checkbox-item"
                        >
                          <el-checkbox :label="size">
                            {{ size }}
                          </el-checkbox>
                          <el-button
                            type="text"
                            size="mini"
                            style="color: red"
                            class="delbtn"
                            @click="handleDelSizeSku(index)"
                          >删除</el-button>
                        </div>
                      </el-checkbox-group>
                    </div>
                    <div class="addsku">
                      <el-row :gutter="10">
                        <el-col :span="3" :offset="0">
                          <el-input
                            v-model.trim="skuColorIpt"
                            placeholder="颜色描述: 比如土豪金"
                            size="mini"
                            clearable
                          />
                        </el-col>
                        <el-col :span="2" :offset="0">
                          <el-button
                            size="mini"
                            @click="handleCreateSkuColor"
                          >创建颜色选项</el-button>
                        </el-col>
                        <el-col :span="3" :offset="0">
                          <el-input
                            v-model="skuSizeIpt"
                            placeholder="大小"
                            size="mini"
                            clearable
                          />
                        </el-col>
                        <el-col :span="2" :offset="0">
                          <el-button
                            size="mini"
                            @click="handleCreateSkuSize"
                          >创建大小选项</el-button>
                        </el-col>
                        <el-col :span="6" :offset="4">
                          <el-button
                            type="primary"
                            size="mini"
                            @click="handleCreateSkuList"
                          >生成sku列表</el-button>
                          <el-button
                            type="primary"
                            size="mini"
                            @click="handleAddSku"
                          >新增sku</el-button>
                        </el-col>
                      </el-row>
                    </div>
                    <div class="sku-list">
                      <el-table :data="skuList" border stripe size="mini">
                        <el-table-column
                          label="#"
                          width="50"
                          type="index"
                          fixed="left"
                        />
                        <el-table-column label="图片" width="120">
                          <template slot-scope="scope">
                            <div>
                              <el-upload
                                ref="uploadSkuImgs"
                                action="http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss"
                                :headers="token"
                                accept=".png,.jpg,.jpeg,.webp"
                                :show-file-list="false"
                                :on-success="
                                  (res) => {
                                    handleSkuImageSuccess(scope.row, res);
                                  }
                                "
                              >
                                <img
                                  v-if="scope.row.pic"
                                  :src="scope.row.pic"
                                  alt=""
                                  srcset=""
                                  class="sku-pic"
                                >
                                <i
                                  v-else
                                  class="el-icon-plus upload-sku-icon"
                                />
                              </el-upload>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="颜色" width="200">
                          <template slot-scope="scope">
                            <div>
                              <el-input v-model="scope.row.color" clearable />
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="大小" width="200">
                          <template slot-scope="scope">
                            <div>
                              <el-input v-model="scope.row.size" clearable />
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="库存" width="200">
                          <template slot-scope="scope">
                            <div>
                              <el-input v-model="scope.row.stock" clearable />
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="预警库存" width="200">
                          <template slot-scope="scope">
                            <div>
                              <el-input
                                v-model="scope.row.lowStock"
                                clearable
                              />
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="锁定库存" width="200">
                          <template slot-scope="scope">
                            <div>
                              <el-input
                                v-model="scope.row.lockStock"
                                clearable
                              />
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="sku编码" width="200">
                          <template slot-scope="scope">
                            <div>
                              <el-input v-model="scope.row.skuCode" clearable />
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="价格" width="200">
                          <template slot-scope="scope">
                            <div>
                              <el-input v-model="scope.row.price" clearable />
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="销量" width="200">
                          <template slot-scope="scope">
                            <div>
                              <el-input v-model="scope.row.sale" clearable />
                            </div> </template></el-table-column>
                        <el-table-column label="操作" width="200" fixed="right">
                          <template slot-scope="scope">
                            <div>
                              <el-button
                                type="text"
                                size="mini"
                                style="color: red"
                                @click="handleDelSkuItem(scope.row.id)"
                              >
                                删除</el-button>
                            </div>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 步骤三 -->
            <div v-show="currentStep == 3" class="stepthree">
              <el-form-item label="商品详情" size="normal">
                <Tinymce v-model="productForm.detailMobileHtml" />
              </el-form-item>
              <el-form-item label="备注" size="normal">
                <el-input
                  v-model="productForm.note"
                  type="textarea"
                  placeholder=""
                  size="normal"
                  clearable
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="footer">
          <el-button
            v-show="currentStep != 1"
            size="mini"
            @click="handlePrevStep"
          >返回上一步</el-button>
          <el-button
            v-show="currentStep == 1"
            type="primary"
            size="mini"
            @click="handleNextStep"
          >下一步,填写库存信息</el-button>
          <el-button
            v-show="currentStep == 2"
            type="primary"
            size="mini"
            @click="handleNextStep"
          >下一步,填写移动端详情</el-button>
          <el-button
            v-show="currentStep == 3"
            type="primary"
            size="mini"
            @click="doSave"
          >提交保存</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid'
import Tinymce from '@/components/Tinymce'

import { getToken } from '@/utils/auth'
import {
  getAllCategory,
  findAllBrand,
  addProductAndSkus,
  productSkusDetail
} from '@/api/product/detail/index'
export default {
  components: {
    Tinymce
  },
  data() {
    return {
      currentStep: 1,
      rules: {},
      productForm: {
        weight: 0,
        pic: '',
        originalPrice: 0,
        lowStock: 10, // 库存预警
        sort: 99999, // 排序
        serviceIds: [],
        albumPics: [],
        detailMobileHtml: '', // 移动端详情
        note: '', // 备注
        promotionType: 0,
        promotionPrice: 0 // 活动价格
      },
      skuList: [],
      categorys: [], // 商品分类
      brandList: [], // 品牌列表
      uploadImages: [], // 上传的文件
      skuColorIpt: '',
      skuColors: [], // 商品颜色
      checkedColors: [], // 被选中的颜色
      skuSizeIpt: '',
      skuSizes: [], // 商品大小
      checkedSkuSizes: [], // 被选中的大小
      selectCategary: {}
    }
  },
  computed: {
    token() {
      return { token: getToken() }
    },
    brand() {
      return this.brandList.find(
        (item) => item.id === this.productForm.brandId
      )
    },
    category() {
      return this.categorys.find(
        (item) => item.id === this.productForm.productCategoryId
      )
    }
  },
  created() {
    this.id = this.$route.params.id

    console.log(this.$route)

    this.getProductCategory()
    this.getAllBrand()
    if (this.id) {
      this.getProductDetail()
    }
  },
  methods: {
    async getProductDetail() {
      const { success, data, message } = await productSkusDetail(this.id)
      if (success) {
        this.productForm = data.product
      } else {
        this.$message.error(message)
      }
    },
    // 获取商品分类
    async getProductCategory() {
      const { success, data, message } = await getAllCategory()
      if (success) {
        const lejuCategorys = data.items.find(
          (item) => item.category.name === '乐居'
        )
        console.log(lejuCategorys)
        if (lejuCategorys) {
          this.categorys = lejuCategorys.children
        }
      } else {
        this.$message.error(message)
      }
    },
    // 获取所有品牌
    async getAllBrand() {
      const { success, data, message } = await findAllBrand()
      if (success) {
        this.brandList = data.items
      } else {
        this.$message.error(message)
      }
    },
    // 上传缩略图
    handleUploadPicSuccess(res) {
      console.log(res)
      if (res.success) {
        this.productForm.pic = res.data.fileUrl
      }
    },
    onExceed() {
      this.$message.error('上传图片数量不能超过5张')
    },
    handleImageSuccess(res, file, files) {
      console.log('files:', files)
      this.uploadImages = files.map((file) => {
        return {
          ...file,
          name: file.name,
          path: file.response.data.fileUrl
        }
      })
    },
    // 删除图片
    handleDelImage(idx) {
      this.uploadImages.splice(idx, 1)
    },
    // 新建skuColor
    handleCreateSkuColor() {
      if (this.skuColorIpt) {
        this.skuColors.push(this.skuColorIpt)
        this.skuColorIpt = ''
      }
    },
    // 删除skuColor
    handleDelColorSku(index) {
      this.skuColors.splice(index, 1)
    },
    // 新建skuSize
    handleCreateSkuSize() {
      if (this.skuSizeIpt) {
        this.skuSizes.push(this.skuSizeIpt)
        this.skuSizeIpt = ''
      }
    },
    //  删除skuSize
    handleDelSizeSku(index) {
      this.skuSizes.splice(index, 1)
    },
    // 生成sku列表
    handleCreateSkuList() {
      if (this.skuList.length) {
        this.$confirm('此操作将清空sku列表,并生成新的列表, 是否继续?', '提示', {
          type: 'warning'
        }).then(() => {
          this.skuList = []
          this.handleAddSku()
        })
      } else {
        this.handleAddSku()
      }
    },
    // 新增sku
    handleAddSku() {
      if (!this.checkedColors.length || !this.checkedSkuSizes.length) {
        this.$message.error('没有选择sku设置')
        return
      }
      for (let i = 0; i < this.checkedColors.length; i++) {
        for (let j = 0; j < this.checkedSkuSizes.length; j++) {
          console.log(this.checkedColors[i], this.checkedSkuSizes[j])
          this.skuList.push({
            id: uuidv4(),
            lockStock: 10, // 锁定库存
            lowStock: 10, // 库存警戒线
            pic: '', // 图片
            price: 0, // 当前价格
            sale: 10, // 销量
            skuCode: '', // sku的编码,手动填写
            stock: 1000, // 库存,
            color: this.checkedColors[i],
            size: this.checkedSkuSizes[j]
          })
        }
      }
    },
    // 删除skulist item
    handleDelSkuItem(id) {
      this.skuList = this.skuList.filter((el) => el.id !== id)
    },
    // sku图片上传
    handleSkuImageSuccess(item, res) {
      if (res.success) {
        item.pic = res.data.fileUrl
      }
    },
    // 下一步
    handleNextStep() {
      this.currentStep++
    },
    // 上一步
    handlePrevStep() {
      this.currentStep--
    },

    async doSave() {
      const skuList = this.skuList.map((item) => {
        item.spData = JSON.stringify([
          {
            key: '颜色',
            value: item.color
          },
          {
            key: '大小',
            value: item.size
          }
        ])
        delete item.id
        return item
      })
      const saveObj = {
        pmsSkuStockList: skuList,
        product: {
          ...this.productForm,
          brandName: this.brand.name,
          productCategoryName: this.category.name,
          price: this.productForm.originalPrice,
          albumPics: this.uploadImages
            .map((el) => {
              return el.path
            })
            .join(','),
          serviceIds: this.productForm.serviceIds.join(','),
          sale: 10,
          stock: 666,
          subTitle: '二级标题', // 二级标题
          unit: '台' // 单位,比如 斤/辆/台
        }
      }

      console.log('saveObj:', saveObj)
      const { success, message } = await addProductAndSkus(saveObj)
      if (success) {
        this.$message.success('保存成功')

        this.$router.push('/product/list')
      } else {
        this.$message.error(message)
      }
    }
  }
}
</script>
<style lang="scss" scope>
.product-detail {
  .header {
    width: 100%;
    background: #fff;
    overflow: hidden;
    .steps {
      margin: 30px auto;
      width: 60%;
      .el-step {
        flex-basis: 50% !important;
        &:last-child {
          flex-basis: auto !important;
          flex-shrink: 0;
          flex-grow: 0;
        }
      }
    }
  }
  .content {
    margin: 30px;
    .header {
      font-size: 16px;
      padding: 10px 0;
      border-bottom: 1px solid #e5e5e5;
      margin-bottom: 30px;
    }
    .el-input-number {
      width: 100%;
    }
    .uploader .el-upload {
      cursor: pointer;
      position: relative;
    }
    .pic,
    .uploader-icon {
      width: 148px;
      height: 148px;
      display: flex;
      font-size: 24px;
      justify-content: center;
      align-items: center;
      border: 1px dashed #c0ccda;
    }

    .from {
      label {
        font-weight: normal;
      }
      .el-select {
        display: block;
      }
      .imgs {
        display: flex;
        .item {
          margin-right: 20px;
          width: 148px;
          height: 148px;
          position: relative;
        }
        .el-icon-close {
          font-size: 20px;
          position: absolute;
          border-radius: 50%;
          right: -10px;
          top: -10px;
          color: red;
          border: 1px solid red;
        }
      }
      .size-sku,
      .color-sku {
        display: flex;
        .title {
          margin-right: 10px;
        }
        .checkbox-item {
          margin-right: 20px;
          display: inline-block;
          .delbtn {
            margin-left: 8px;
          }
        }
      }
      .upload-sku-icon {
        width: 100px;
        height: 100px;
        display: flex;
        font-size: 24px;
        justify-content: center;
        align-items: center;
      }

      .sku-pic {
        width: 100px;
        height: 100px;
      }
    }
  }
  .footer {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
